package com.yuanqi.controller;

import com.yuanqi.domain.AccountsPayableNew;
import com.yuanqi.service.AccountsPayableNewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/finance/accounts-payable-new")
@CrossOrigin(origins = "*")
public class AccountsPayableNewController {
    
    @Autowired
    private AccountsPayableNewService accountsPayableNewService;
    
    @GetMapping
    public ResponseEntity<Map<String, Object>> getAccountsPayablePage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String supplierName,
            @RequestParam(required = false) Integer overdueStatus,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate dueDate) {
        
        try {
            Pageable pageable = PageRequest.of(page - 1, size);
            Page<AccountsPayableNew> result = accountsPayableNewService.getAccountsPayablePage(
                supplierName, overdueStatus, dueDate, pageable
            );
            
            Map<String, Object> response = new HashMap<>();
            response.put("content", result.getContent());
            response.put("totalPages", result.getTotalPages());
            response.put("totalElements", result.getTotalElements());
            response.put("currentPage", page);
            response.put("size", size);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<AccountsPayableNew> getById(@PathVariable Long id) {
        try {
            AccountsPayableNew accountsPayable = accountsPayableNewService.getById(id);
            return ResponseEntity.ok(accountsPayable);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    @GetMapping("/supplier/{supplierId}")
    public ResponseEntity<Map<String, Object>> getBySupplierId(@PathVariable Long supplierId) {
        try {
            var accountsPayable = accountsPayableNewService.getBySupplierId(supplierId);
            Map<String, Object> response = new HashMap<>();
            response.put("content", accountsPayable);
            response.put("totalElements", accountsPayable.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
    
    @GetMapping("/overdue")
    public ResponseEntity<Map<String, Object>> getOverdueAccounts() {
        try {
            var overdueAccounts = accountsPayableNewService.getOverdueAccounts();
            Map<String, Object> response = new HashMap<>();
            response.put("content", overdueAccounts);
            response.put("totalElements", overdueAccounts.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
    
    @PostMapping
    public ResponseEntity<AccountsPayableNew> create(@RequestBody AccountsPayableNew accountsPayable) {
        try {
            AccountsPayableNew created = accountsPayableNewService.create(accountsPayable);
            return ResponseEntity.ok(created);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<AccountsPayableNew> update(@PathVariable Long id, @RequestBody AccountsPayableNew accountsPayable) {
        try {
            AccountsPayableNew updated = accountsPayableNewService.update(id, accountsPayable);
            return ResponseEntity.ok(updated);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        try {
            accountsPayableNewService.delete(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getStatistics() {
        try {
            Map<String, Object> stats = accountsPayableNewService.getStatistics();
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
    
    @GetMapping("/stats/total-payable")
    public ResponseEntity<Map<String, Object>> getTotalPayableAmount() {
        try {
            var totalPayable = accountsPayableNewService.getTotalPayableAmount();
            Map<String, Object> response = new HashMap<>();
            response.put("totalPayable", totalPayable);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
    
    @GetMapping("/stats/total-overdue")
    public ResponseEntity<Map<String, Object>> getTotalOverdueAmount() {
        try {
            var totalOverdue = accountsPayableNewService.getTotalOverdueAmount();
            Map<String, Object> response = new HashMap<>();
            response.put("totalOverdue", totalOverdue);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
    
    @GetMapping("/stats/total-unpaid")
    public ResponseEntity<Map<String, Object>> getTotalUnpaidAmount() {
        try {
            var totalUnpaid = accountsPayableNewService.getTotalUnpaidAmount();
            Map<String, Object> response = new HashMap<>();
            response.put("totalUnpaid", totalUnpaid);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
}
